﻿using AutoMapper;
using B.S.AuthCenter.Api.Read.Application.Command.Menu;
using B.S.AuthCenter.Api.Read.DTOs;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace B.S.AuthCenter.Api.Read.Application.Handler.Menu
{
    public class GetMenuParentHandler : IRequestHandler<GetMenuParentCommand, ApiResult<List<MenuParentDTO>>>
    {
        IBaseRepository<MenuManageModel> menuRepo;
        IMapper mapper;

        public GetMenuParentHandler(IBaseRepository<MenuManageModel> menuRepo, IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<MenuParentDTO>>> Handle(GetMenuParentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<MenuParentDTO>> res=new ApiResult<List<MenuParentDTO>>();
            res.Msg = "查询菜单列表成功";
            res.Code=ApiEnum.Success;
            var allmenu=menuRepo.GetAll().Where(c=>!c.IsDeleted).OrderByDescending(c=>c.Id).ToList();
            var menunamedict = allmenu.ToDictionary(m => m.Id, m => m.MenuName);
            res.Datas = allmenu.Select(m=>new MenuParentDTO
            {
                Id = m.Id,
                MenuName = m.MenuName,
                Pid = m.Pid,
                MenuParentName=(m.Pid!=0 && menunamedict.ContainsKey(m.Pid)) ? menunamedict[m.Pid]:"",
                Url = m.Url,
                Creator = m.Creator,
                CreatorDate = m.CreatorDate,
                Updator=m.Updator,
                UpdatorDate=m.UpdatorDate,
            }).ToList();
            return Task.FromResult(res);
        }
       
    }
}
